package com.tyqx.detectcputemperaturesendmessage;


import com.profesorfalken.jsensors.JSensors;
import com.profesorfalken.jsensors.model.components.Components;
import com.profesorfalken.jsensors.model.components.Gpu;
import com.profesorfalken.jsensors.model.sensors.Fan;
import com.profesorfalken.jsensors.model.sensors.Temperature;
import com.sun.mail.smtp.SMTPTransport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;

@Component
public class SchedulerGpuSendMessage {

    private static final Logger logger = LoggerFactory.getLogger(SchedulerGpuSendMessage.class);


    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private Constant constant;

    @Value("${emailMessage.fromEmail}")
    private  String fromEmail;

    @Value("${emailMessage.toEmail}")
    private  String toEmail;

    @Value("${emailMessage.username}")
    private  String username;

    @Value("${emailMessage.password}")
    private  String password;

    @Value("${emailMessage.smtpServer}")
    private  String smtpServer;

    private  String toEmailCC = "";

    private  String emailSubject = "gpu温度过高提醒!";

    private  String emailText = "";

    public static Integer temperature = 65;
    //public static Integer temp_upper = 65;
    //public static Integer temp_lower = 35;


    public static Integer scheduler_count = 0;

    public static Boolean send_mail_flag = false;

    //表示每隔秒
    @Scheduled(fixedRate = 60 * 1000 * 1)
    //@Scheduled(fixedDelay = 1000 * 60 * 1)
    public void testTasks() throws Exception {
        logger.info("检测服务器温度定时器开始执行："+dateFormat.format(new Date())+"\n");

        Integer temp_upper = constant.temp_upper;
        Integer temp_lower = constant.temp_lower;

        try{
            boolean flag = false;
            if (send_mail_flag) {
                scheduler_count = (scheduler_count + 1) % 10;
                if (scheduler_count == 0){
                    send_mail_flag = false;
                }
            }

            Components components = JSensors.get.components();

//            List<Cpu> cpus = components.cpus;
//            if (cpus != null) {
//                for (final Cpu cpu : cpus) {
//                    logger.info("Found CPU component: " + cpu.name);
//                    if (cpu.sensors != null) {
//                        logger.info("Sensors: ");
//
//                        //Print temperatures
//                        List<Temperature> temps = cpu.sensors.temperatures;
//                        for (final Temperature temp : temps) {
//                            logger.info(temp.name + ": " + temp.value + " C");
//                            if(temp.value > temperature){
//                                flag = true;
//                                emailText = "cpu name:"+cpu.name +"\ntemp name:" + temp.name +"\ntemp value:"+temp.value;
//                                break;
//                            }
//                        }
//
//                        //Print fan speed
//                        List<Fan> fans = cpu.sensors.fans;
//                        for (final Fan fan : fans) {
//                            logger.info(fan.name + ": " + fan.value + " RPM");
//                        }
//                    }
//                }
//            }

            List<Gpu> gpus = components.gpus;
            if (gpus != null) {
                Map<String, String> map = System.getenv();

                //emailText = map.get("COMPUTERNAME") + ":\n\n\n";
                emailText = constant.component_name + ":\n\n\n";
                for (final Gpu gpu : gpus) {
                    logger.info("Found CPU component: " + constant.component_name);
                    if (gpu.sensors != null) {
                        logger.info("Sensors: ");

                        //Print temperatures
                        List<Temperature> temps = gpu.sensors.temperatures;
                        for (final Temperature temp : temps) {
                            logger.info(temp.name + ": " + temp.value + " C");
                            emailText = emailText + "gpu name:" + gpu.name + "\nsensor name:" + temp.name + "\ntemperature value:" + temp.value + "\n\n";
                            if(temp.value > temp_upper){
                                flag = true;
                                emailSubject = "gpu温度过高提醒!";
                            }

                            if(temp.value < temp_lower){
                                flag = true;
                                emailSubject = "gpu温度过低提醒!";
                            }

                        }

                        //Print fan speed
                        List<Fan> fans = gpu.sensors.fans;
                        for (final Fan fan : fans) {
                            logger.info(fan.name + ": " + fan.value + " RPM");
                        }
                    }
                }
            }

            if (send_mail_flag){
                flag = false;
            }

            if(flag){
                send_mail_flag = true;
                scheduler_count = 0;
                Properties prop = System.getProperties();
                prop.put("mail.smtp.host", smtpServer); //optional, defined in SMTPTransport
                prop.put("mail.smtp.auth", "true");
                prop.put("mail.smtp.starttls.enable", "true");
                prop.put("mail.smtp.ssl.trust", smtpServer);
                prop.put("mail.smtp.port", "25"); // default port 25

                Session session = Session.getInstance(prop, null);
                Message msg = new MimeMessage(session);

                try {

                    // from
                    msg.setFrom(new InternetAddress(fromEmail));

                    // to
                    msg.setRecipients(Message.RecipientType.TO,
                            InternetAddress.parse(toEmail, false));

                    // cc
                    msg.setRecipients(Message.RecipientType.CC,
                            InternetAddress.parse(toEmailCC, false));

                    // subject
                    msg.setSubject(emailSubject);

                    // content
                    msg.setText(emailText);


                    msg.setSentDate(new Date());

                    // Get SMTPTransport
                    SMTPTransport t = (SMTPTransport) session.getTransport("smtp");

                    // connect
                    t.connect(smtpServer, username, password);

                    // send
                    t.sendMessage(msg, msg.getAllRecipients());

                    logger.info("Response: " + t.getLastServerResponse());

                    t.close();

                } catch (MessagingException e) {
                    e.printStackTrace();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        logger.info("检测服务器温度定时器结束执行："+dateFormat.format(new Date())+"\n");
    }
}